package com.kuang.realm;

import com.kuang.dao.impl.UserDaoImpl;
import com.kuang.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserDaoImpl userDaoImpl;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权");
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证");

        // 这里的authenticationToken，其实就是 subject.login(token)中的token；
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        // 从数据库 获取用户信息
        User user = userDaoImpl.getUserByEmail(usernamePasswordToken.getUsername());

        if (user == null) {
            // 此用户不存在
            return null; // 这里shiro会帮我们抛出一个用户不存在的异常UnknownAccountException
        }

        return new SimpleAuthenticationInfo("", user.getPassword(), "");
    }
}
